<?php
/** Yz_SQL_Statement_Select
*
*/

class Yz_SQL_Statement_Update
    extends Yz_SQL_DMLStatement
    implements Yz_SQL_Statement_Interface
{

    const CLAUSE_UPDATE = 'UPDATE';
    const CLAUSE_IGNORE = 'IGNORE';
    const CLAUSE_TABLES = '_tables_';
    const CLAUSE_SET    = 'SET';
    const CLAUSE_VALUES = '_values_';
    const CLAUSE_WHERE  = 'WHERE';
    const CLAUSE_ORDER_BY = 'ORDER BY';
    const CLAUSE_LIMIT  = 'LIMIT';

    protected $clauses = array(
        self::CLAUSE_UPDATE => '',
        self::CLAUSE_IGNORE => '',
        self::CLAUSE_TABLES => '',
        self::CLAUSE_SET    => '',
        self::CLAUSE_VALUES => '',
        self::CLAUSE_WHERE  => '',
        self::CLAUSE_ORDER_BY => '',
        self::CLAUSE_LIMIT  => '',
    );


    /**
     *  @param string table
     *  @param string|null table-alias
     *
     */
    public function update( $table, $alias=null )
    {
        return $this->_table(self::CLAUSE_UPDATE, $table, $alias);
    }


    public function where( $what )
    {
        return $this->_where(self::CLAUSE_WHERE, $what);
    }

    public function orderBy( $what )
    {
        return $this->_orderBy(self::CLAUSE_ORDER_BY, $what);
    }

    public function limit( $limit )
    {
        $limit = Yz_Int::testNotNegative( $limit );
        return $this->_limit(0, $limit);
    }


    public function ignore( $ignore=true )
    {
        $this->clauses[self::CLAUSE_IGNORE] = $ignore ? self::CLAUSE_IGNORE : "";

        return $this;
    }


    /**
     *  @param mixed fields : array[ name => SQL clause ] | string
     *  @param mixed values : null | string
     */
    public function set( $fields, $values=null )
    {
        if (is_string($fields) && is_string($values)) {
            $clause = $fields . '=' . $values;
        } else {
            $fx = new Yz_Hash($fields);
            $clause = $fx
                ->map(function($key,$value) {
                    return $key . '=' . $value;
                })
                ->join(",\n  ");
        }
        $this->sql = null;
        $this->clauses[self::CLAUSE_SET] = self::CLAUSE_SET;
        $this->clauses[self::CLAUSE_VALUES] = '  ' . $clause;
        return $this;
    }



    /** isComplete() : is it possible to execute sql statement ?
     *
     *  @return string SQL
     */
    protected function isComplete()
    {
        debug();

        $clauses = $this->clauses;

        return ! ( "" === $clauses[self::CLAUSE_UPDATE] || "" === $clauses[self::CLAUSE_SET] );
    } // isComplete


} // class

